package com.fjh.controller;

import com.fjh.anno.Log;
import com.fjh.domain.SysMenu;
import com.fjh.service.SysMenuService;
import com.fjh.model.MenuAuth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "菜单管理")
@RestController
@RequestMapping("sys/menu")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @GetMapping("nav")
    @ApiOperation("获取菜单和权限")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    @Log(operation = "加载菜单和权限")
    public ResponseEntity<MenuAuth> loadMenuAndAuth(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取当前身份
        String userId = authentication.getPrincipal().toString();
        //查询当前用户的树菜单
        List<SysMenu> menuList=sysMenuService.loadTreeByUserId(userId);
        //获取当前的权限信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //转换权限集合
        List<String> auths = authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        //组装对象返回
        MenuAuth menuAuth = new MenuAuth();
        menuAuth.setAuthorities(auths);
        menuAuth.setMenuList(menuList);
        return ResponseEntity.ok(menuAuth);
    }
}
